package com.wande.dataplatform.filecollection.alert;

import com.wande.dataplatform.filecollection.config.FileCollectionProperties;
import com.wande.dataplatform.filecollection.performance.PerformanceMonitor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 告警监控任务
 * 定期检查系统状态并发送告警
 *
 * @author wande
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AlertMonitorTask {

    private final AlertService alertService;
    private final PerformanceMonitor performanceMonitor;
    private final FileCollectionProperties properties;

    /**
     * 监控系统资源
     * 每5分钟执行一次
     */
    @Scheduled(fixedRate = 300000)
    public void monitorSystemResources() {
        if (!properties.getPerformance().getMonitorEnabled()) {
            return;
        }

        try {
            Runtime runtime = Runtime.getRuntime();
            
            // 检查内存使用率
            long totalMemory = runtime.totalMemory();
            long freeMemory = runtime.freeMemory();
            long usedMemory = totalMemory - freeMemory;
            long maxMemory = runtime.maxMemory();
            
            double memoryUsagePercent = (double) usedMemory / maxMemory * 100;
            
            // 内存使用率超过85%时告警
            if (memoryUsagePercent > 85) {
                alertService.sendResourceAlert("内存", memoryUsagePercent);
                log.warn("High memory usage detected: {}%", String.format("%.2f", memoryUsagePercent));
            }
            
            // 记录性能指标
            if (log.isDebugEnabled()) {
                log.debug("System resources - Memory: {}%, Threads: {}", 
                    String.format("%.2f", memoryUsagePercent), Thread.activeCount());
            }
            
        } catch (Exception e) {
            log.error("Failed to monitor system resources", e);
        }
    }

    /**
     * 输出性能指标日志
     * 根据配置的间隔执行
     */
    @Scheduled(fixedRateString = "${file-collection.performance.metrics-log-interval:300}000")
    public void logPerformanceMetrics() {
        if (!properties.getPerformance().getMonitorEnabled()) {
            return;
        }

        try {
            var stats = performanceMonitor.getStatistics();
            
            log.info("Performance Metrics - Tasks: {}, Files: {}, Records: {}, Success Rate: {}%",
                stats.get("totalTasks"),
                stats.get("totalFiles"),
                stats.get("totalRecords"),
                calculateSuccessRate(stats));
            
            if (stats.containsKey("parseRecordsPerSecond")) {
                log.info("Throughput - Parse: {} records/s, Load: {} records/s",
                    stats.get("parseRecordsPerSecond"),
                    stats.get("loadRecordsPerSecond"));
            }
            
        } catch (Exception e) {
            log.error("Failed to log performance metrics", e);
        }
    }

    /**
     * 计算成功率
     */
    private String calculateSuccessRate(java.util.Map<String, Object> stats) {
        Object totalTasks = stats.get("totalTasks");
        Object successTasks = stats.get("successTasks");
        
        if (totalTasks instanceof Number && successTasks instanceof Number) {
            long total = ((Number) totalTasks).longValue();
            long success = ((Number) successTasks).longValue();
            
            if (total > 0) {
                return String.format("%.2f", (double) success / total * 100);
            }
        }
        
        return "0.00";
    }
}
